<template>
	<div class="__input-container">
		<div ref="__input"
			data-root
			contenteditable="true"
			class="__input-wrap"
			@click="inputClick"
			@blur="inputBlur"
			@keyup="inputKeyup"
			@input="inputChange($event)"
			@keydown="keydown($event)"
			@paste="paste"></div>
		<span class="__placeholder" v-show="isEmpty">{{placeholder}}</span>
	</div>
</template>

<script>
import props from './lib/props'
import { paseDom, blobToURL, uuid } from './lib/utils'
import Clipboard from './lib/clipboard-paste'
import Cursor from './lib/get-cursor'
export default {
	name: "im-input-box",
	props: props,
	data() {
		return {
			isIe: false,
			cursor: null, // 光标对象
			empty: '<p data-empty=""><br></p>', // 空占位符
			isEmpty: true, // 是否为空
			input: null // 输入框对象
		}
	},
	created() {
		const isIe = !!window.ActiveXObject || 'ActiveXObject' in window
		this.isIe = isIe
	},
	mounted() {
		this.init()
	},
	methods: {
		init() {
			let input = this.$refs.__input
			this.input = input
			this.input.focus()			
			this.cursor = Cursor(this.input) // 初始化光标方法
			if(this.defaultText) {
				this.setContent(this.defaultText)
			} else {
				this.insertEmpty()
			}
		},
		// 清除内容
		clearContent() {
			this.input.innerHTML = ''
			this.insertEmpty()			
			this.cursor.resetRange() // 重置光标对象
		},
		// 设置默认内容
		setContent(text) {
			this.input.innerHTML = ''
			const el = paseDom(this.empty)
			el.innerText = text
			this.input.appendChild(el)
			this.isEmpty = false
			el.focus()
			this.cursor.setRangeToEnd(el)
		},		
		// 插入空占位符
		insertEmpty() {
			const empty = paseDom(this.empty)
			this.input.appendChild(empty)
			this.isEmpty = true
			this.input.focus()
		},
		/**
		 * 处理插入的内容
		 * 图片添加UUID方便需要上传成功后替换URL
		 */
		beforeInsert(data) {
			const id = uuid(32, 32)
			let node = null
			if(data.type === 'text') {
				node = document.createTextNode(data.content)
				return node
			}
			if(data.type === 'node') {
				// let node 
			}
			if(data.type === 'image') {				
				node = document.createElement('img')
				node.src = data.content
				node.setAttribute('data-id', data.uuid || id)
				node.setAttribute('data-type', data.imgKey || 'image')
				return node
			}
		},
		/**
		 * 插入内容
		 * @param {String} data.type 类型（text, image）
		 * @param {String} data.content 内容（文本内容，图片URL）
		 * @param {String} data.imgKey 图片的类型（自定义，比如：表情，图片）
		 * @param {String} data.uuid 图片类型的uuid(用于图片上传后替换本地图片)
		 */
		insertContent(data) {
			const el = this.beforeInsert(data)
			if(data.type == 'text') {
				this.insertText(el)
			}
			if(data.type == 'image') {
				this.insertImage(el)
			}
			if(data.type == 'node') {
				this.insertNode(el)
			}
		},
		// 插入节点
		insertNode(el) {
			console.log(el)
		},
		// 插入文字
		insertText(el) {
			this.cursor.insertElement(el)
		},
		// 插入图片
		insertImage(el) {
			this.cursor.insertElement(el)
		},
		// 监听内容
		// const a = empty.hasAttribute('data-empty')
		inputChange(e) {
			this.isEmpty = false
			const innerHTML = e.target.innerHTML
			this.$emit('change', e.target.innerHTML)
			if(!innerHTML) {
				this.insertEmpty()
			}
			if(innerHTML == this.empty) {
				this.isEmpty = true
			}
		},
		// 生成粘贴内容
		createPasteContent(type, context) {
			let params = {
				type: type
			}
			if(type === 'text') {
				params.content = context
				this.insertContent(params)
			} else {
				blobToURL(context).then(res => {
					params.content = res
					this.insertContent(params)
				})
			}
		},
		// 点击
		inputClick() {
			this.cursor.getCursor()
		},
		// 失焦
		// TODO 失去焦点的时候,不覆盖键盘抬起
		inputBlur() {
			this.cursor.getCursor()
		},
		inputKeyup(e) {
			this.cursor.getCursor()
		},
		// 粘贴
		paste(e) {
			e.preventDefault()
			const clipboard = Clipboard(e)
			const content = clipboard.getContent
			const { type, file, text } = content
			if(!type) return
			if(type === 'text') {
				this.createPasteContent(type, text)
				return
			}
			if(!file) return
			const size = file.size / 1024 /1024
			// 图片
			if(type === 'image' && this.pasteImg && size < this.pasteImgSize) {
				this.createPasteContent(type, file)
				this.$emit('pasteFileChange', content)
				return
			}
			// 文件
			if(type === 'file' && this.pasteFile && size < this.pasteFileSize) {
				this.$emit('pasteFileChange', content)
				return
			}
		},
		// 按下键盘
		keydown(e) {
			// if(this.wrapCode == 'ctrlEnter') {

			// }
		}
	}
}
</script>

<style>
.__input-container {
	padding: 0;
	margin: 0;
	border: 0;
	width: 100%;
	height: 100%;
	position: relative;
}
.__input-wrap {
	height: 100%;
	width: 100%;
	outline: none;
	padding: 5px;
	box-sizing: border-box;
	overflow: auto;
	word-wrap: break-word;
}
.__input-wrap::-webkit-scrollbar {
	width: 4px;
}
.__input-wrap::-webkit-scrollbar-track-piece {
	background-color: #e4e7ed;
}
.__input-wrap::-webkit-scrollbar-thumb {
	background-color: #909293;
	border-radius: 2px;
}
.__input-wrap:focus {
	outline: none;
}
.__input-wrap:empty::before {
	content: attr(placeholder);
	color: #9aa2ab;
}
.__input-wrap:focus .__input-wrap:empty::before {
	content: none;
}
.__input-wrap > p {
	padding: 0;
	margin: 0;
}
.__input-wrap > p > img[data-type="image"] {
	max-width: 100%;
	width: 200px;
	cursor: pointer;
}
.__input-wrap > p > img[data-type="emoji"]:hover {
	width: 24px;
	height: 24px;
}
.__input-wrap > p > img[data-type="image"]:hover {
	box-shadow: 0 0 5px #333;
}
.__placeholder {
	color: #d4d4d4;
    position: absolute;
    font-size: 11pt;
    line-height: 22px;
    left: 5px;
    top: 5px;
    user-select: none;
    z-index: -1;
}
</style>
